<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Category;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class CategoryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Category(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('title');
            $grid->column('end_time');
            $grid->column('desc');
            $grid->column('url');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('title')->width('4');
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $id = $actions->getKey();
                $actions->append("<a href='export/{$id}' target='_blank'><i class='fa fa-paper-plane'></i> 导出</a>");
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Category(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('end_time');
            $show->field('desc');
            $show->field('url');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Category(), function (Form $form) {
            $form->display('id');
            $form->text('title')->required();
            $form->datetime('end_time')->required();
            $form->textarea('desc')->required();

            $form->display('created_at');
            $form->display('updated_at');
            $form->saved(function (Form $form, $result) {
                if ($form->isCreating()) {
                    // 自增ID
                    $newId = $result;
                    if (!$newId) {
                        return $form->error('数据保存失败');
                    }
                    \App\Models\Category::query()->where('id', $newId)->update(['url' => env('APP_URL') . '/antis/' . $newId]);
                    return $form->response()->redirect('category');
                }
            });
        });
    }
}
